/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.sgf.utils.bsession;

import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.ICafSessionService;
import io.iec.edp.caf.core.session.SessionType;
import io.iec.edp.caf.core.session.core.CAFSessionThreadHolder;
import io.iec.edp.caf.tenancy.api.ITenantService;
import io.iec.edp.caf.tenancy.api.entity.Tenant;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;

/**
 * 功能描述:
 *
 * @ClassName: BackendSessionUtils
 * @Author: Fynn Qi
 * @Date: 2021/6/23 12:43
 * @Version: V1.0
 */
@Slf4j
public class BackendSessionUtils {
    private static final String BACKEND_SESSION_USER_ID = "abc";

    public static void wrapFirstTenantBackendSession(Consumer<Tenant> consumer) {
        ICafSessionService cafSessionService = SpringBeanUtils.getBean(ICafSessionService.class);
        ITenantService tenantService = SpringBeanUtils.getBean(ITenantService.class);
        CafSession oldSession = CAFSessionThreadHolder.getCurrentSession();

        try {
            List<Tenant> tenants = tenantService.getAllTenants("zh-CHS");
            if (tenants != null && tenants.size() > 0) {
                Tenant tenant = tenants.get(0);
                if (oldSession != null) {
                    //如果当前存在session，则先清空
                    CAFSessionThreadHolder.purge();
                }
                if (CAFContext.current.getCurrentSession() == null) {
                    //如果session已经没了，就创建一个bsesion
                    CafSession cafSession = cafSessionService.create(tenant.getId(), BACKEND_SESSION_USER_ID, "zh-CHS", new HashMap<>(), SessionType.backend);
                    CAFSessionThreadHolder.setCurrentSession(cafSession);
                    log.info("create bsession with tenant=" + tenant.getId() + ",userId=" + BACKEND_SESSION_USER_ID + ", lang=zh-CHS, sessionId=" + cafSession.getId());
                } else {
                    //如果还存在，就用当前的。这个分支应该不会走到。
                    CafSession curSession = CAFContext.current.getCurrentSession();
                    log.warn("exist session with tenant={}, userId={}, lang={}, sessionType={}", curSession.getTenantId(), curSession.getUserId(), curSession.getLanguage(), curSession.getSessionType());
                }

                //TODO 使用现有session时，tenant信息错误
                consumer.accept(tenant);
            } else {
                log.warn("not fount tenants");
            }
        } finally {
            try {
                CafSession curSession = CAFSessionThreadHolder.getCurrentSession();
                if (curSession != null) {
                    cafSessionService.deleteById(curSession.getId());
                    CAFSessionThreadHolder.purge();
                    log.info("delete bsession with sessionId=" + curSession.getId());
                }
            } catch (Throwable e) {
                log.warn("删除BSession出错，等待过期自动删除", e);
            }
            if (oldSession != null) {
                //如果原来存在Session，则设回之前的Session
                CAFSessionThreadHolder.setCurrentSession(oldSession);
            }
        }
    }

}
